﻿using System.Net;
using Common;
using StackExchange.Redis;

namespace BaseRepository.Redis
{
    public sealed class RedisManager
    {
        private static readonly ConnectionMultiplexer _instance;
        private RedisManager()
        {
        }

        static RedisManager()
        {
            var redisConfig = Appsettings.app<RedisConfig>("Redis");
            if (redisConfig==null || redisConfig.RedisConnectionStrings==null)
            {
                throw new Exception("redis配置错误，请检查");
            }
            if (!redisConfig.Enable)
            {
                throw new Exception("请打开redis的配置");
            }
            // 添加端点
            var endPoints = new List<EndPoint>();
            foreach (var connectionString in redisConfig.RedisConnectionStrings)
            {
                var address = connectionString.Split(":", StringSplitOptions.RemoveEmptyEntries);
                if (address.Length!=2)
                {
                    throw new Exception("redis ip地址配置有误！请检查");
                }
                endPoints.Add(new IPEndPoint(IPAddress.Parse(address[0]), address[1].ToInt32()));
            }
            
            var config = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
                AllowAdmin = true,
                ConnectTimeout = 15000,//改成15s
                SyncTimeout = 5000,
                Password = redisConfig.Password,//Redis数据库密码
                EndPoints = new EndPointCollection(endPoints) // connectionString 为IP:Port 如”192.168.2.110:6379”
            };
            _instance = ConnectionMultiplexer.Connect(config);
        }

        public static ConnectionMultiplexer Instance
        {
            get => _instance;
        }
    }
    /// <summary>
    /// redis配置文件映射类
    /// </summary>
    public class RedisConfig
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enable { get; set; }
        /// <summary>
        /// 连接字符串  ip+端口
        /// </summary>
        public List<string>? RedisConnectionStrings { get; set; }
        /// <summary>
        /// redis密码
        /// </summary>
        public string? Password { get; set; }

        /// <summary>
        /// 初始库
        /// </summary>
        public int DataBase { get; set; } = 0;
    }
}
